const app = getApp();
const util      = require("util.js")
const storage     = require("storage.js")
const constant  = require("../constant.js")

// 判断是否 需要授权 按钮
// 当：globalData.needAuth = true && currentPage.needAuth = true  && app.Setting res.authSetting['scope.userInfo'] 不存在
// 则：需要展示授权按钮
function checkAuthBtn(target) {
  
  // 不需要授权，就不授权
  if (app.globalData.needAuth ===  false) {
    target.setData({
      showAuthBtn: false
    })
    return false;
  }

  // 当前页面是否需要授权，不需要就不授权
  if (target.data.needAuthBtn === false) {
    target.setData({
      showAuthBtn: false
    })
    return false
  }

  wx.getSetting({
    success: function (res) {
      if (res.authSetting['scope.userInfo']) {
        console.log("已经授权，可以直接调用 getUserInfo 获取头像昵称")
        // 这里直接调用并且更改doAuth逻辑
        if (doCheckSession()) {
          try {
            var sessionResult = wx.getStorageSync(storage.keys.session)
            var openidResult = wx.getStorageSync(storage.keys.openid)
            if (sessionResult && openidResult && sessionResult != "" && openidResult != "") {
              app.globalData.authSuccess = function() {
                wx.redirectTo({
                  url: 'pages/profile/profile',
                })
              };
              app.globalData.authFail = function () {
                $.showToast("授权失败！")
              };
              app.globalData.authKey = sessionResult;
              target.setData({
                showAuthBtn: true
              })
            } else {
              target.setData({
                showAuthBtn: true
              })
              doWxLogin(function() {
                return true
              }, function() {
                $.showToast("授权失败！")
              })
            }
          } catch (e) {
            console.log(e);
            target.setData({
              showAuthBtn: true
            })
            doWxLogin(function () {
              return true
            }, function () {
              $.showToast("授权失败！")
            })
          }

        } else {
          target.setData({
            showAuthBtn: true
          })
          doWxLogin(function () {
            return true
          }, function () {
            $.showToast("授权失败！")
          })
        }
        
      } else {
        target.setData({
          showAuthBtn: true
        })
        doWxLogin(function () {
          return true
        }, function () {
          $.showToast("授权失败！")
        })

      }
    }
  })
}

// check登录态是否过期
function doCheckSession() {
  wx.checkSession({
    success: function () {
      debugger
      return true;
    },fail: function () {
      debugger
      console.log("登录态过期, 重新登录")
      return false;
    }
  })
}

// 执行wx.login（静默登录） 获取 code, 同时转化为sessionKey
function doWxLogin(success, fail) {
  var that = this;
  wx.login({
    success: function (res) {
      if (res.code) {
        console.log("小程序静默登录成功, 跳转到成功处理逻辑...")
        //_handleWeAppLoginSuccess(res, success, fail) // 发起成功回调
        console.log("小程序登录成功, 开始根据code [" + res.code + "]获取session与openid")
        wx.request({
          url: constant.api(app.globalData.pord).auth.prepare + res.code,
          method: 'GET',
          success: function (resp) {

            if (resp.data.code == "0") {
              var session = resp.data.data.session_key;
              var openid = resp.data.data.openid;
              app.globalData.authSuccess = success;
              app.globalData.authFail = fail;
              app.globalData.authKey = session;
              try {
                wx.setStorageSync(storage.keys.session, session)
                wx.setStorageSync(storage.keys.openid, openid)
                console.log("缓存session与openid成功，直接跳转到成功回调函数")
                typeof success == "function" && success(session);
              } catch (e) {
                console.log(e)
                console.log("缓存session与openid失败: " + e)
                typeof fail == "function" && fail();
              }
            } else {
              console.log("获取weapp-api项目的session与openid失败")
              console.log("request openid occurs error with code[" + res.data.code + "] message[" + res.data.message + "]")
              typeof fail == "function" && fail();
            }
          },
          fail: function (response) {
            console.log("获取session与openid网络请求失败")
            console.log(response)
            typeof fail == "function" && fail();
          }
        })

      } else {
        console.log("小程序静默登录获取数据失败, 跳转到失败处理逻辑...")
        console.log(res)
        typeof fail == "function" && fail("微信登录失败");
      }
    },
    fail: function (res) {
      console.log("小程序发起静默登录失败, 跳转到失败处理逻辑...")
      typeof fail == "function" && fail("微信登录失败");
    }
  })
}

/**
 *
 */
function doWeAppLogin(success, fail) {

  var that = this
  wx.checkSession({
    success: function () {
      try {
        var sessionResult = wx.getStorageSync(storage.keys.session)
        var openidResult = wx.getStorageSync(storage.keys.openid)
        if (sessionResult && openidResult && sessionResult != "" && openidResult != "") {
          console.log("登录中，storage也存在数据, 直接返回成功回调函数")
          typeof success == "function" && success(sessionResult, openidResult)
        } else {
          _doLogin(success, fail);
        }
      } catch (e) {
        console.log(e)
        console.log("登录中，storage不存在数据, 重新登录")
        _doLogin(success, fail);
      }
    },
    fail: function () {
      console.log("登录态过期, 重新登录")
      _doLogin(success, fail);
    }
  })
}

function _doLogin(success, fail) {
  var that = this;
  wx.login({
    success: function (res) {
      if (res.code) {
        console.log("小程序登录成功, 跳转到成功处理逻辑...")
        _handleWeAppLoginSuccess(res, success, fail) // 发起成功回调
      } else {
        console.log("小程序登录失败, 跳转到失败处理逻辑...")
        _hanldeWeappLoginFail(res, fail)
      }
    },
    fail: function (res) {
      console.log("小程序登录失败, 跳转到失败处理逻辑...")
      console.log(res)
      _hanldeWeappLoginFail(res, fail)
    }
  })
}

// 处理小程序登录成功
function _handleWeAppLoginSuccess(res, success, fail) {

  console.log("小程序登录成功, 开始根据code [" + res.code + "]获取session与openid")
  wx.request({
    url: constant.api(app.globalData.pord).auth.prepare + res.code,
    method: 'GET',
    success: function (res) {

      if (res.data.code == "0") {
        var session = res.data.data.session_key;
        var openid = res.data.data.openid;

        try {
          wx.setStorageSync(storage.keys.session, session)
          wx.setStorageSync(storage.keys.openid, openid)
          console.log("缓存session与openid成功，直接跳转到成功回调函数")
          typeof success == "function" && success(session);
        } catch (e) {
          console.log(e)
          console.log("缓存session与openid失败: " + e)
        }
      } else {
        console.log("获取session与openid失败")
        console.log("request openid occurs error with code[" + res.data.code + "] message[" + res.data.message + "]")
      }
    },
    fail: function (response) {
      console.log("获取session与openid网络请求失败")
      console.log(response)
    }
  })
}

// 处理小程序登录失败
function _hanldeWeappLoginFail(res, fail) {
  console.log("直接返回失败回调函数")
  typeof fail == "function" && fail(res)
}

function authRequest(target) {
  // save auth reidrect page into storgae
  try {
    //wx.setStorageSync(storage.keys.authRedirect, that.data.redirect ? that.data.redirect : '../../pages/profile/profile')
    this.getUserInfo({}, function (unionid) {
      target.setData({
        unionid: unionid
      })
      wx.setStorageSync(storage.keys.authRedirect, "")
      setTimeout(function () {
        wx.redirectTo({
          url: target.data.redirect ? target.data.redirect : '../../pages/profile/profile'
        })
      }, 2000)
    }, function () {
      console.log("auth get userinfo faild");
      wx.redirectTo({
        url: '../../pages/error-page/error-page',
      })
    })
  } catch (e) {
    console.log(e)
  }
}

function getUserInfo(params, success, fail) {
  debugger
  doWeAppLogin(
    function (sessionKey) {

      console.log("小程序静默授权成功， 开始准备获取用户信息");

      wx.getSetting({
        success: function (res) {
          if (res.authSetting['scope.userInfo']) {
            console.log("已经授权，可以直接调用 getUserInfo 获取头像昵称")
            wx.getUserInfo({
              withCredentials: true,
              success: function (res) {
                _handleGetUserInfoSuccess(res.iv, res.encryptedData, sessionKey, success, fail)
              },
              fail: function () {
                openUserInfo();
              }
            })
          } else {
            // 开始弹窗授权
            app.globalData.authSuccess = success;
            app.globalData.authFail = fail;
            app.globalData.authKey = sessionKey;
            wx.redirectTo({
              url: params.authUrl ? params.authUrl : '../auth/auth',
            })
          }
        }
      })
    },
    function () {
      console.log("do weapp Login faild, get none user info");
    }
  )
}

function openUserInfo() {
  wx.openSetting({
    success: (res) => {
      console.log(res);
    },
    fail: (res) => {
      console.log(res);
    },
    complete: (res) => {
      console.log(res);
    },
  })
}

function _handleGetUserInfoSuccess(iv, encryptedData, sessionKey, success, fail, stopredirect) {
  debugger
  try {
    var unionid = wx.getStorageSync(storage.keys.unionid)
    var mobile = wx.getStorageSync(storage.keys.mobile)
    if (unionid) {
      if(mobile) {
        typeof success == "function" && success(sessionKey)
      } else {
        _requestWechatAccountInfo(iv, encryptedData, sessionKey, success, fail, stopredirect);
      }
    } else {
      _requestWechatAccountInfo(iv, encryptedData, sessionKey, success, fail, stopredirect);
    }
  } catch (e) {
    console.log(e);
    _requestWechatAccountInfo(iv, encryptedData, sessionKey, success, fail, stopredirect);
  }
}

function _requestWechatAccountInfo(iv, encryptedData, sessionKey, success, fail, stopredirect) {
  wx.request({
    url: constant.api(app.globalData.pord).auth.login,
    data: {
      'session-key': sessionKey,
      'iv': iv,
      'encrypted-data': encryptedData
    },
    method: 'POST',
    header: {
      'content-type': 'application/x-www-form-urlencoded'
    },
    success: function (res) {
      if (res.data.code == "0") {
        try {
          var data = res.data.data;
          console.log("get wechat data" + data);
          wx.setStorageSync(storage.keys.unionid, data.account.unionid)
          var mobile = wx.getStorageSync(storage.keys.mobile)
          if(mobile) {
            typeof success == "function" && success(data.account.unionid)
          } else {
            wx.request({
              url: constant.api(app.globalData.pord).url + '/get-mobile?unionid=' + data.account.unionid,
              method: 'POST',
              data: {
                headimgurl: data.account.headimgurl,
                nickname: data.account.nickname
              },
              header: {
                'content-type': 'application/json'
              },
              dataType: 'json',
              responseType: 'text',
              success: function (res) {
                if (res.data.code == "0" && res.data.data.mobile) {
                  wx.setStorageSync(storage.keys.mobile, res.data.data.mobile);
                  wx.request({
                    url: constant.api(app.globalData.pord).url + '/is-student?unionid=' + data.account.unionid,
                    method: 'POST',
                    dataType: 'json',
                    responseType: 'text',
                    success: function (res) {
                      if (res.data.code == "0") {
                        var isStudent = res.data.data.isStudent;

                        if (isStudent) {
                          wx.reLaunch({
                            url: '/pages/profile/profile'
                          })
                         } else {
                           wx.reLaunch({
                             url: '/pages/malls/malls-index/malls-index'
                           })
                         }
                      } else {
                        wx.showToast({
                          title: res.data.message,
                          icon: 'none',
                          duration: 1000
                        })
                      }
                    },
                    fail: function (res) {
                      wx.showToast({
                        title: '请求数据失败',
                        icon: 'none',
                        duration: 1000
                      })
                    }
                  })

                } else {
                  wx.reLaunch({
                    url: '/pages/mobile-bind/mobile-bind',
                  })
                }
              },
              fail: function () {
                wx.reLaunch({
                  url: '/pages/mobile-bind/mobile-bind',
                })
              }
            })

          }
        } catch (e) {
          console.log(e)
          typeof fail == "function" && fail()
        }
      } else {
        console.log("request userinfo occurs error with code[" + res.data.code + "] message[" + res.data.message + "]")
      }
    },
    fail: function (respnse) {
      //console.log("request userinfo faild");
      typeof fail == "function" && fail()
    }
  })
}

// function _requestUserInfo(unionid, success, fail, stopredirect) {
//   wx.request({
//     url: constant.get("userApi"),
//     data: {
//       'unionid': unionid
//     },
//     method: 'POST',
//     header: {
//       'content-type': 'application/x-www-form-urlencoded'
//     },
//     success: function (response) {
//       util.formatResponse(response, function (data) {
//         var app = getApp();

//         if (data.user.email) {
//           store.set(constant.get("emailKey"), data.user.email)
//         }
//         store.set(constant.get("adminKey"), data.user.admin)
//         store.set(constant.get("nicknameKey"), data.user.nickname)

//         store.set(constant.get("unionidKey"), data.user.unionid)
//         store.set(constant.get("accountKey"), data.user.id)

//         if (!stopredirect) {
//           typeof success == "function" && success(data)
//         }
//       }, function (code, message) {
//         //console.log("request userinfo occurs error with code[" + code + "] message[" + message + "]")
//         typeof fail == "function" && fail(data)
//       })
//     },
//     fail: function (response) {
//       //console.log("request userinfo faild");
//       typeof fail == "function" && fail(data)
//     }
//   })
// }

module.exports = {
  checkAuthBtn: checkAuthBtn,
  login: doWeAppLogin,
  getUserInfo: getUserInfo,
  authRequest: authRequest,
  _handleGetUserInfoSuccess: _handleGetUserInfoSuccess
}
